package cms.dao;

import cms.common.PageData;
import cms.util.DButils;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述：ORM数据操作类【findAll,findOne,findPage,addInfo,updateInfo】
 *
 * @Author: 余辉
 * @Date: 2021/4/5 10:21
 */
public class BaseDao {


    /**
     * 功能描述: 适用于单表的一条数据更新，添加，删除
     * @Author: yuhui  2021/4/5 14:36
     */
    public static boolean executeUpdate(String sql,Object[] args){
        boolean resFlag = false;
        Connection conn = null;
        PreparedStatement pred = null;
        try{
            conn = DButils.createConnection();
            pred = conn.prepareStatement(sql);
            if(args!=null && args.length!=0){
                for (int i = 0; i < args.length; i++) {
                    pred.setObject((i + 1), args[i]);
                }
            }
            int rows = pred.executeUpdate();
            if(rows > 0){
                resFlag = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                pred.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return resFlag;
    }
    private static Object invokeFromField(Class cls,ResultSet rs) throws IllegalAccessException, InstantiationException, SQLException, NoSuchFieldException {
        Object o = cls.newInstance();
        ResultSetMetaData metaData = rs.getMetaData();
        int col_cun = metaData.getColumnCount();
        for(int u=1;u<=col_cun;u++){
            String columnName = metaData.getColumnName(u);
            Field declaredField = cls.getDeclaredField(columnName);
            declaredField.setAccessible(true);
            declaredField.set(o,rs.getObject(columnName));
        }
        return o;
    }
    /**
    * 功能描述: 查询所有数据
    * @Author: yuhui  2021/4/5 14:24
    */
    public static <T> List<T> findAll(String sql,Class<T> cls,Object[] args){
        Connection conn = null;
        PreparedStatement pred = null;
        List<T> lis = new ArrayList<>();

        try{
            conn = DButils.createConnection();
            pred = conn.prepareStatement(sql);
            if(args!=null && args.length!=0){
                for(int y=0;y<args.length;y++){
                    pred.setObject(y+1,args[y]);
                }
            }
            ResultSet rs = pred.executeQuery();

            while(rs.next()){
                lis.add((T)invokeFromField(cls,rs));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }finally {
            try {
                pred.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return lis;
    }

    /**
    * 功能描述: 查询一条数据
    * @Author: yuhui
    * @Date: 2021/4/5 11:24
    */
    public static <T> List<T> findOne(String sql,Class cls,Object[] args){
        return findAll(sql,cls,args);
    }

    /**
    * 功能描述: 分页查询数据
    * @Author: yuhui
    * @Date: 2021/4/5 14:17
    */
    public static PageData findPage(String sql, String sql_page, Class cls, Object[] args, PageData pageData){
        List lis = findAll(sql_page,cls,args);
        int num = findCount(sql);
        pageData.setLis(lis);
        pageData.setPageCount(num);
        pageData.setPageNum(num%pageData.getPageSize() == 0 ? num/pageData.getPageSize() : num/pageData.getPageSize()+1);
        return pageData;
    }

    /**
    * 功能描述: 删除数据，支持批量删除
    * @Author: yuhui  2021/4/5 14:49
    */
    public static boolean deleInfo(String sql,Object[] args){
        boolean resFlag = false;
        Connection conn = null;
        PreparedStatement pred = null;

        try{
            conn = DButils.createConnection();
            pred = conn.prepareStatement(sql);
            for(int i=0;i<args.length;i++){
                pred.setObject(i+1,args[i]);
                pred.addBatch();
            }
            int[] ints = pred.executeBatch();
            if(ints.length > 0){
                resFlag = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                pred.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return resFlag;
    }

    public static int findCount(String sql){
        Connection conn = null;
        PreparedStatement prep = null;
        ResultSet rs = null;
        int total = 0;
        try{
            conn = DButils.createConnection();
            prep = conn.prepareStatement(sql);
            rs = prep.executeQuery();
            rs.next();
            total = rs.getInt(1);
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            try {
                rs.close();
                prep.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return total;
    }
}
